package com.xinxing.learning.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinxing.learning.security.exception.CaptchaNotMatchException;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

/**
 * 扩展验证码登录filter
 */
public class LoginCaptchaFilter extends UsernamePasswordAuthenticationFilter {
    private static final String SPRING_SECURITY_CAPTCHA_KEY = "captcha";

    private String captchaParameter = SPRING_SECURITY_CAPTCHA_KEY;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)
                || request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
            try {
                Map<String, String> userInfo = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                String username = userInfo.get(this.getUsernameParameter());
                String password = userInfo.get(this.getPasswordParameter());
                String verifyCode = userInfo.get(this.getCaptchaParameter());
                String sessionVerifyCode = (String) request.getSession().getAttribute("captcha");
                if (Objects.nonNull(verifyCode)
                        && Objects.nonNull(sessionVerifyCode)
                        && verifyCode.equalsIgnoreCase(sessionVerifyCode)) {

                    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                    // Allow subclasses to set the "details" property
                    setDetails(request, authRequest);
                    return this.getAuthenticationManager().authenticate(authRequest);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        throw new CaptchaNotMatchException("验证码错误!");
    }

    public String getCaptchaParameter() {
        return captchaParameter;
    }

    public void setCaptchaParameter(String captchaParameter) {
        this.captchaParameter = captchaParameter;
    }
}
